﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CronusModel;
using Cronus.ViewModel.Data;

namespace Cronus.ViewModel
{
    public class TaskActivities
    {
        //*** Constants ***//
        //*** Static ***//
        //*** Member Variables ***//
        private DataModel _DataModel;

        //*** Properties ***//
        //*** Events ***//
        //*** Constructors ***//
        public TaskActivities(DataModel aDataModel)
        {
            _DataModel = aDataModel;
        }

        //*** Abstract Methods ***//
        //*** Methods ***//
        /// <summary>
        /// Creates a task with the given name if one does not already exist.  If a task already
        /// exists, the existing task is returned.
        /// </summary>
        /// <param name="taskName">The name of the task to create.</param>
        /// <returns>Task with the given name.</returns>
        public Task GetOrCreateTask(string taskName)
        {
            var aTaskQuery = new QueryTaskInformation(_DataModel);
            Task aTask = aTaskQuery.GetTaskWithName(taskName);
            if (null == aTask)
            {
                aTask = Task.CreateTask(_DataModel, taskName);
            }
            return aTask;
        }

        /// <summary>
        /// Starts timing the given task. If the task does not exist, it is created.
        /// </summary>
        /// <param name="taskName">Task to start timing; if the task does not exist it is created.</param>
        /// <returns>Pointer to the Activity object created to track timing.</returns>
        public Activity StartTiming(string taskName)
        {
            return StartTiming(GetOrCreateTask(taskName));
        }

        /// <summary>
        /// Starts timing the given task.
        /// </summary>
        /// <param name="task">Task to start timing [not null].</param>
        /// <returns>Pointer to the Activity object created to track timing.</returns>
        public Activity StartTiming(Task task)
        {
            if (null == task)
                throw new ArgumentNullException("task", "The given task to time cannot be null.");

            var activity = Activity.CreateNewActivity(task);
            activity.StartTime = DateTime.Now;

            return activity;
        }

        /// <summary>
        /// Stops timing any active activities.
        /// </summary>
        public void StopTiming()
        {
            // 1) Query for any activities currently being timed.
            var query = new QueryActivityInformation(_DataModel);
            var activities = query.GetActivitiesBeingTimed();

            // 2) Set the completion time on all the activities to now.
            DateTime now = DateTime.Now;
            foreach (var activity in activities)
                activity.EndTime = now;
        }
    }
}
